package nil.ed.simulator.request.ui.jfx.controller;

import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.MenuBar;
import javafx.stage.FileChooser;
import lombok.Getter;
import lombok.Setter;
import nil.ed.simulator.request.enums.events.EventMode;
import nil.ed.simulator.request.enums.events.EventType;
import nil.ed.simulator.request.event.Event;
import nil.ed.simulator.request.event.bus.EventBus;
import nil.ed.simulator.request.guice.GuiceManager;
import nil.ed.simulator.request.repo.RuntimeRepo;
import nil.ed.simulator.request.ui.jfx.manager.ControllerManager;
import nil.ed.simulator.request.ui.jfx.manager.FxManager;
import nil.ed.simulator.request.ui.jfx.ui.Controller;

import java.io.File;
import java.net.URL;
import java.util.Collections;
import java.util.ResourceBundle;

public class MenuController extends MenuBar implements Controller, Initializable {

    @Setter
    @Getter
    private ControllerManager controllerManager;

    public void importHandler(ActionEvent e) {
        FileChooser chooser = new FileChooser();

        File selected = chooser.showOpenDialog(FxManager.getStage());
        if (selected != null) {
            GuiceManager.INJECTOR.getInstance(EventBus.class).publish(Event.builder()
                    .eventType(EventType.FILE_IMPORT)
                    .source(null)
                    .eventMode(EventMode.SYNC)
                    .data(Collections.singletonList(selected))
                    .build());
        }
    }

    public void exportHandler(ActionEvent e) {
        if (!RuntimeRepo.QQ_REPO.isFinish()) {
            Alert dialog = new Alert(Alert.AlertType.WARNING);
            dialog.setContentText("任务进度未完成！");
            dialog.setTitle("任务进度警告");
            dialog.show();
            return;
        }
        FileChooser chooser = new FileChooser();
        File selected = chooser.showSaveDialog(FxManager.getStage());
        if (selected != null) {
            GuiceManager.INJECTOR.getInstance(EventBus.class).publish(Event.builder()
                    .eventType(EventType.FILE_EXPORT)
                    .source(null)
                    .eventMode(EventMode.SYNC)
                    .data(selected)
                    .build());
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        ControllerManager.addController(this);
    }
}
